package com.xzzz.backend.bsms.loadbalancer;

import com.xzzz.common.lb.CpuWeightLoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * 作为自定义的LB配置, 不需要使用 {@link Configuration}
 * @author xzzz
 */
public class CustomCpuWeightLBConfig {

    /**
     * 使用自定义负载均衡策略
     *
     * @param environment               环境
     * @param loadBalancerClientFactory lbClient 工厂
     * @return 自定义LB策略
     */
    @Bean
    public ReactorLoadBalancer<ServiceInstance> customLoadBalancer(Environment environment,
                                                                   LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new CpuWeightLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }

}
